using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ApiServer.SwaggerExt;
using ApiServer.Utilitys.Filters;
using ApiServer.Utilitys.InitDatabaseExt;
using AutoMapper;
using BusinessInterface;
using BusinessServer;
using Common;
using Common.EnumEntity;
using DTOModels.User;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Models.Entity;
using Npgsql;
using SqlSugar;

namespace ApiServer.Controllers.ServiceAPI
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [Authorize(
        AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,
        Policy = "btnPolicy"
    )]
    public class UseController : ControllerBase
    {
        private readonly IMapper _IMapper;
        private readonly IMenuManagerService _IMenuManagerService;
        private readonly IUserManagerService _IUserManagerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_iMenuManagerService"></param>
        /// <param name="iuserManagerService"></param>
        /// <param name="iMapper"></param>
        /// <param name="iUserManagerService"></param>
        public UseController(IMenuManagerService _iMenuManagerService, IUserManagerService iuserManagerService, IMapper iMapper, IUserManagerService iUserManagerService)
        {
            _IMenuManagerService = _iMenuManagerService;
            _IMapper = iMapper;
            _IUserManagerService = iuserManagerService;
        }


        /// <summary>
        /// 获取用户分页
        /// </summary>
        /// <param name="sqlSugarClient"></param>
        /// <param name="userManagerService"></param>
        /// <param name="mapper"></param>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageindex:int}/{pageSize:int}")]
        [Route("{pageindex:int}/{pageSize:int}/{searchString?}")]

        public async Task<JsonResult> GetUserPagingList(
            [FromServices] ISqlSugarClient sqlSugarClient,
            [FromServices] IUserManagerService userManagerService,
            [FromServices] IMapper mapper,
            int pageindex,
            int pageSize,
            string? searchString=""
        )
        {
            //原生写法
            //var list=await sqlSugarClient.Queryable<Sys_User>()
            //   .Where(u => u.UserType == (int)UserTypeEnum.GeneralUser)
            //   .WhereIF(!string.IsNullOrWhiteSpace(searchString), u => !string.IsNullOrWhiteSpace(u.Name) && u.Name.Contains(searchString))
            //   .OrderBy(u => u.CreateTime)
            //   .ToPageListAsync(pageindex, pageSize);
            //var result = new JsonResult(new ApiResultData<List<Sys_User>>() { Data = list, Success = true, Message = "用户分页列表" });
            Expressionable<Sys_User> expressionable = new Expressionable<Sys_User>();

            //过滤掉管理员的数据
            expressionable.And(u => u.UserType == (int)UserTypeEnum.GeneralUser);

            expressionable.AndIF(!string.IsNullOrWhiteSpace(searchString), u => !string.IsNullOrWhiteSpace(u.Name) && u.Name.Contains(searchString!));

            //expressionable.And(u=>u.Status==(int)StatusEnum.Normal);

            PagingData<Sys_User> paging = userManagerService.QueryPage<Sys_User>(expressionable.ToExpression(), pageSize, pageindex, c => c.CreateTime, false);
            PagingData<SysUserDto> pagingResult = mapper.Map<PagingData<Sys_User>, PagingData<SysUserDto>>(paging);
            var result = new JsonResult(new ApiResultData<PagingData<SysUserDto>>() { Data = pagingResult, Success = true, Message = "用户分页列表" });

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 添加普通用户的信息
        /// </summary>
        /// <param name="userManagerService"></param>
        /// <param name="mapper"></param>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        [HttpPost]
         [CustomValidateParaActionFilter]  //统一封装的一个验证空间控件
        public async Task<JsonResult> AddUserAsync([FromServices] IUserManagerService userManagerService, [FromServices] IMapper mapper, SysUserDto userDTO)
        {
            Sys_User adduser = mapper.Map<SysUserDto, Sys_User>(userDTO);
            adduser.Password = MD5Encrypt.Encrypt(adduser.Password);
            adduser.Status = userDTO.IsEnabled ? (int)StatusEnum.Normal : (int)StatusEnum.Frozen;
            adduser.UserType = (int)UserTypeEnum.GeneralUser;

            Sys_User user = userManagerService.Insert(adduser);
            var result = new JsonResult(new ApiResultData<Sys_User>() { Data = adduser, Success = true, Message = "添加用户" });

            if (user.UserId <= 0)
            {
                result = new JsonResult(new ApiResultData<Sys_User>() { Data = adduser, Success = false, Message = "添加用户失败" });
            }

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userManagerService"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete()]
        [Route("{userId:int}")]
        public async Task<JsonResult> DeleteUserAsync( int userId)
        {
            Sys_User user = _IUserManagerService.Find<Sys_User>(userId);
            user.Status = (int)StatusEnum.Deleted; //置为删除状态
            var result = new JsonResult(new ApiResultData<Sys_User>() { Data = user, Success = false, Message = "删除失败" });
            if (await _IUserManagerService.UpdateAsync<Sys_User>(user))
            {
                result = new JsonResult(new ApiResultData<Sys_User>() { Data = user, Success = true, Message = "删除用户信息" });
            }
            return await Task.FromResult(result);
        }


        /// <summary>
        /// 获取所有的菜单按钮树结构数据
        /// 用于给某用户直接分配菜单权限
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="userId"></param>
        /// <returns></returns> 
        [HttpGet()]
        [Route("{userId:int}")]
        [AllowAnonymous]
        public async Task<JsonResult> GetAllMenuBtnTreeListAsync( int userId)
        {
            (List<UserMenuBtnDto>, List<Guid>) tup = await _IUserManagerService.GetAllMenuBtnTreeListAsync(userId);
            var result = new JsonResult(new ApiResultData<List<UserMenuBtnDto>>()
            {
                Data = tup.Item1,
                OValue = tup.Item2,
                Message = "获取树形结构",
                Success = true
            });
            return await Task.FromResult(result);
        }


        /// <summary>
        /// 分配用户菜单
        /// </summary>
        /// <param name="userManagerService"></param>
        /// <param name="setUserMenue"></param>
        /// <returns></returns> 
        [HttpPost]
        [Route("{userId:int}")]
        public async Task<JsonResult> SetUserMenuAndBtnAsync(SetUserMenuBtnDto setUserMenue)
        {
            bool bResult = await _IUserManagerService.SetUserMenuAndBtnAsync(setUserMenue);
            string message = "操作失败";
            if (bResult)
            {
                message = "操作成功";
            }
            JsonResult result = new JsonResult(new ApiResult()
            {
                Success = bResult,
                Message = message
            });
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <param name="userRoleMenuService"></param>
        /// <param name="selectRoles"></param>
        /// <returns></returns>
        //[Function(MenuTypeEnum.Button, "设置用户角色")]
        [HttpPut]
        [Route("SetUserRoleAsync")]
        public async Task<JsonResult> SetUserRoleAsync([FromServices] IUserRoleMenuService userRoleMenuService, SetUserRoleModel selectRoles)
        {
            ApiResult apiResult = userRoleMenuService.SetUserRole(selectRoles.UserId, selectRoles.SelectRoleIdList);
            JsonResult result = new JsonResult(apiResult);
            return await Task.FromResult(result);
        }

    }
}
